import 'dart:io';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:go_pet/src/features/login/services/snack_bar.dart';
import 'package:go_pet/src/features/login/view/widgets/components/my_button.dart';
import 'package:image_picker/image_picker.dart';

class PostPet extends StatefulWidget {
  const PostPet({super.key});

  @override
  State<PostPet> createState() => _PostPetState();
}

class _PostPetState extends State<PostPet> {
  TextEditingController _controller = TextEditingController(text: '@');
  String _name = '';
  String _description = "";
  String _tgID = "";

  final _formKey = GlobalKey<FormState>();
  File? file;

  handleChooseImageFromGallery() async {
    final picker = ImagePicker();
    final pickedImage = await picker.pickImage(source: ImageSource.gallery);

    if (pickedImage != null) {
      // Обработайте выбранное изображение
      setState(() {
        file = File(pickedImage.path);
      });
    } else {
      // Обработайте случай, если пользователь не выбрал изображение
    }
  }

  Future<void> uploadPic(BuildContext context, String name, String description,
      String tgId) async {
    try {
      SnackBarService.showSnackBar(
        context,
        'Пост загружен',
        false,
      );
      Navigator.of(context).pop();
      var storage = FirebaseStorage.instance;
      TaskSnapshot taskSnapshot = await storage.ref(file!.path).putFile(file!);
      final String downloadUrl = await taskSnapshot.ref.getDownloadURL();

      await FirebaseFirestore.instance.collection("posts").add({
        "ImgUrl": downloadUrl,
        "Title": name,
        "Description": description,
        "TgID": tgId,
        "TimeStamp": Timestamp.now()
      });
    } catch (e) {
      print(e);
      SnackBarService.showSnackBar(
        context,
        'Неизвестная ошибка! Попробуйте еще раз или обратитесь в поддержку.',
        true,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Создать Пост'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Form(
              key: _formKey,
              child: Column(
                children: [
                  file != null
                      ? Image.file(file!, height: 250)
                      : GestureDetector(
                          onTap: handleChooseImageFromGallery,
                          child: Container(
                            height: 250,
                            width: 200,
                            color: Colors.grey,
                            child: Icon(Icons.photo_camera),
                          )),
                  TextFormField(
                    decoration: const InputDecoration(hintText: "Имя"),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Введите имя животного';
                      }
                      return null;
                    },
                    onSaved: (value) {
                      _name = value!;
                    },
                  ),
                  TextFormField(
                    decoration: const InputDecoration(hintText: "Описание"),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Введите описание';
                      }
                      return null;
                    },
                    onSaved: (value) {
                      _description = value!;
                    },
                  ),
                  TextFormField(
                    controller: _controller,
                    decoration: const InputDecoration(hintText: "@telegram"),
                    validator: (value) {
                      if (value == null ||
                          value.isEmpty ||
                          !value.contains("@")) {
                        return 'Введите телеграмм';
                      }
                      return null;
                    },
                    onSaved: (value) {
                      _tgID = value!;
                    },
                  ),
                ],
              ),
            ),
            MyButton(
              text: "Отправить",
              onTap: () {
                if (_formKey.currentState!.validate()) {
                  if (file == null) {
                    SnackBarService.showSnackBar(
                      context,
                      'Загрузите картинку',
                      true,
                    );
                    return;
                  }
                  _formKey.currentState!.save();
                  uploadPic(context, _name, _description, _tgID);
                }
              },
            )
          ],
        ),
      ),
    );
  }
}
